package com.micro.platform.starter.config.loadbalance.rest;

import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.server.reactive.ServerHttpRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class HeaderInterceptor implements ClientHttpRequestInterceptor {

    private ApplicationContext applicationContext;
    public HeaderInterceptor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        Map requestHeader = getRequestHeader();
        if(null != requestHeader) {
            httpRequest.getHeaders().putAll(requestHeader);
        }
        return clientHttpRequestExecution.execute(httpRequest, bytes);
    }

    private Map getRequestHeader() {
        try {
            ServerHttpRequest bean = this.applicationContext.getBean(ServerHttpRequest.class);
            return bean.getHeaders();
        }catch (Exception ex){

        }
        try {
            HashMap<String, String> stringStringHashMap = new HashMap<>();
            HttpServletRequest bean = this.applicationContext.getBean(HttpServletRequest.class);
            Enumeration<String> headerNames = bean.getHeaderNames();
            while (headerNames.hasMoreElements()){
                String s = headerNames.nextElement();
                stringStringHashMap.put(s, bean.getHeader(s));
                return stringStringHashMap;
            }
        }catch (Exception ex){

        }
        return null;
    }
}